<template>
  <div>
    <el-table
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      size="small"
      :data="tableData"
      border
      style="margin-bottom: 20px"
      max-height="350px"
    >
      <el-table-column
        v-if="isIndex"
        type="index"
        label="序号"
        width="60"
        show-overflow-tooltip
      />
      <el-table-column
        show-overflow-tooltip
        v-for="item in tableConfig"
        :key="item.prop"
        :label="item.label"
        :width="item.width"
      >
        <template #default="scope">
          <span
            v-if="item.handle"
            :style="{
              color: item.colors ? item.colors[scope.row[item.prop]] : '',
            }"
          >
            {{ item.list[scope.row[item.prop]] }}
          </span>
          <span v-else>
            {{ scope.row[item.prop] }}
          </span>
        </template></el-table-column
      >
      <el-table-column
        :width="operateWidth"
        v-if="isOperate"
        show-overflow-tooltip
        label="操作"
      >
        <template #default="scope">
          <slot :scope="scope" name="operate"></slot>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      small
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :page-sizes="[4, 8, 10, 20]"
      :background="true"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, defineProps } from "vue";
import axios from "@/utils/http";
import { CODE } from "@/utils/StatusCode";

const props = defineProps({
  tableConfig: Object,
  queryApi: String,
  isIndex: Boolean,
  isOperate: Boolean,
  operateWidth: Number,
});

const { tableConfig, queryApi, isIndex, isOperate, operateWidth } =
  toRefs(props);

const tableData = ref([]);
let pagination = reactive({
  currentPage: 1,
  pageSize: 8,
});
const total = ref(0);

let inputParams = {};
const onSearch = (data: any) => {
  inputParams = data;
  pagination.currentPage = 1;
  doQuery();
};
defineExpose({ onSearch });

const doQuery = async () => {
  let params = Object.assign(pagination, inputParams);

  const res = await axios({
    url: queryApi?.value,
    method: "get",
    params: params,
  });
  if (res.code == CODE.OK) {
    tableData.value = res.data.records;
    total.value = res.data.total;
  }
};
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  doQuery();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  doQuery();
};
</script>

<style lang="less" scoped></style>
